package com.hillky.serialize.impl;

import com.alibaba.fastjson2.JSON;
import com.hillky.exceptions.SerializeException;
import com.hillky.serialize.Serializer;
import com.hillky.transport.message.RequestPayload;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Arrays;

@Slf4j
public class JsonSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        byte[] result = JSON.toJSONBytes(object);
        if (log.isDebugEnabled()) {
            log.debug("对象【{}】json序列化已经完成,长度是【{}】", object, result.length);
        }
        return result;

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {

        if (bytes == null||clazz==null) {
            return null;
        }
        T object = JSON.parseObject(bytes, clazz);
        if(log.isDebugEnabled()){
            log.debug("类【{}】json反序列化已经完成",clazz);
        }
        return object;
    }


    public static void main(String[] args) {
        Serializer serializer=new JsonSerializer();

        RequestPayload payload=new RequestPayload();
        payload.setInterfaceName("xxxx");
        payload.setMethodName("yyyy");
        payload.setParametersValue(new Object[]{"xxxx"});

        // java类（class文件），json不能序列化

        byte[] bytes = serializer.serialize(payload);

        System.out.println(Arrays.toString(bytes));

        RequestPayload requestPayload = serializer.deserialize(bytes, RequestPayload.class);
        System.out.println(requestPayload);
    }
}
